<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <!-- <el-form-item label="单据号">
          <el-input
            v-model="searchParam.recordCode"
            placeholder="请输入单据号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="原始凭证号">
          <el-input
            v-model="searchParam.originalVoucherNo"
            placeholder="请输入原始凭证号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="设备大类">
          <el-input
            v-model="searchParam.assetKind"
            placeholder="请输入设备大类"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="设备主键">
          <el-input
            v-model="searchParam.assetId"
            placeholder="请输入设备主键"
            clearable
            @keyup.enter="search"
          />
        </el-form-item> -->
        <el-form-item label="设备编码">
          <el-input
            v-model="searchParam.assetCode"
            placeholder="请输入设备编码"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="searchParam.assetName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <!-- <el-form-item label="变更类型">
          <el-input
            v-model="searchParam.changeType"
            placeholder="请输入变更类型"
            clearable
            @keyup.enter="search"
          />
        </el-form-item> -->
        <el-form-item label="变更前状态">
          <el-select
            v-model="searchParam.statusBeforeChange"
            placeholder="请选择变更前状态"
            clearable
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('EquipStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="变更后状态">
          <el-select
            v-model="searchParam.statusAfterChange"
            placeholder="请选择变更后状态"
            clearable
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('EquipStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <!-- <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        > -->
        <!-- <el-button
          class="ml-3"
          @click="
            useDownload(
              '/eam/mtassetstatuschange/export',
              '设备状态变更记录',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
        <el-button type="success" @click="excelBoxOpen">导入 </el-button> -->
        <el-dialog
          :close-on-click-modal="false"
          title="设备状态变更记录数据导入"
          v-model="excelBox"
          width="555px"
        >
          <div>
            <el-button
              @click="
                useDownload(
                  '/eam/equStatusChange/exportTemp',
                  '设备状态变更记录上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              设备状态变更记录上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        :maxHeight="tableHeight"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column
          label="单据号"
          sortable
          prop="recordCode"
          min-width="100"
          show-overflow-tooltip
          align="left"
        >
        </el-table-column>

        <el-table-column
          label="设备编码"
          prop="assetCode"
          min-width="120"
          show-overflow-tooltip
          sortable
          align="left"
        >
        </el-table-column>
        <el-table-column
          label="设备名称"
          prop="assetName"
          min-width="120"
          show-overflow-tooltip
          sortable
          align="left"
        >
        </el-table-column>
        <!-- <el-table-column
          label="变更类型"
          prop="changeType"
          min-width="120"
          show-overflow-tooltip
        >
        </el-table-column> -->

        <el-table-column
          label="变更前状态"
          prop="statusBeforeChange"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{ useDictionary("EquipStatus", scope.row.statusBeforeChange) }}
          </template>
        </el-table-column>
        <el-table-column
          label="变更后状态"
          prop="statusAfterChange"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{ useDictionary("EquipStatus", scope.row.statusAfterChange) }}
          </template>
        </el-table-column>
        <el-table-column
          label="变更原因"
          prop="changeReason"
          min-width="120"
          show-overflow-tooltip
          sortable
          align="left"
        >
        </el-table-column>

        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
          sortable
        >
        </el-table-column>

        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
        </el-table-column>
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
          sortable
        >
        </el-table-column>

        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="60" align="center">
          <template #default="scope">
            <!-- <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button> -->
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
              >
                <i-ep-search />
              </el-button>
            </el-tooltip>
            <!-- <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <devicechangestatus-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDownload,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { filterOrder } from "@/utils/commonHooks";
defineOptions({
  name: "EQUDEVICECHANGESTATUS",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/equStatusChange/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  recordCode: "",
  originalVoucherNo: "",
  assetKind: "",
  assetId: "",
  assetCode: "",
  assetName: "",
  changeType: "",
  statusBeforeChange: "",
  statusAfterChange: "",
};

const deleteParam = {
  api: "/eam/equStatusChange/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});
// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/equStatusChange/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开设备状态变更记录表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改设备状态变更记录";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增设备状态变更记录";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开设备状态变更记录表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "设备状态变更记录详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// 导入excel
const uploadApi = "/eam/equStatusChange/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/equStatusChange/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
</script>
